﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using GlimpseWcf.Core;
using Newtonsoft.Json;

namespace GlimpseWcf.Client
{
    public static class WcfResponseManager
    {
        public static void AddWcfResponseData(string wcfCall, WcfGlimpseResponse response, HttpContextBase context)
        {
            if (context.Items["WcfGlimpseResponses"] == null)
                context.Items["WcfGlimpseResponses"] = new Dictionary<string, Dictionary<string, object>>();

            var tabStore = ((Dictionary<string, Dictionary<string, object>>)context.Items["WcfGlimpseResponses"]);

            wcfCall = string.IsNullOrWhiteSpace(wcfCall) ? "WcfTab" : wcfCall;
            wcfCall = tabStore.ContainsKey(wcfCall) ?  wcfCall + (tabStore.Count(t => t.Key.Contains(wcfCall)) + 1) : wcfCall;
            tabStore.Add(wcfCall, ConvertWcfGlimpseResponseToDictionary(response));
        }

        private static Dictionary<string, object> ConvertWcfGlimpseResponseToDictionary(WcfGlimpseResponse response)
        {
            return response.TabResults.ToDictionary(result => result.Name, result => JsonConvert.DeserializeObject(result.Data,new JsonSerializerSettings{ TypeNameHandling = TypeNameHandling.All, NullValueHandling = NullValueHandling.Include}));

            //var loadedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(r => r.GetTypes()).Select(t => t.AssemblyQualifiedName).ToList();
            //var dict = response.TabResults.ToDictionary(result => result.Name, result => /*loadedTypes.Contains(result.ObjectType) ?*/ JsonConvert.DeserializeObject(result.Data, Type.GetType(result.ObjectType)) /*: JsonConvert.DeserializeObject(result.Data)*/);
            //dict.Add("Types", response.TabResults.ToDictionary(r => r.Name, t => t.ObjectType));
        }

        public static Dictionary<string, Dictionary<string, object>> GetGlimpseResponsesForContext(HttpContextBase context)
        {
            return context.Items["WcfGlimpseResponses"] as Dictionary<string, Dictionary<string, object>>;
        }
    }
}
